package com.example.timewidget.widgets

import android.annotation.SuppressLint
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.widget.RemoteViews
import com.example.timewidget.R
import kotlinx.coroutines.Runnable

class TimeEasyWidgetProvider : AppWidgetProvider() {
    val TAG = "czyy"
    private val totalFrames = 5
    private var curFrame = 0
    val handler = Handler(Looper.getMainLooper())

    // 周期性更新根据配置
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
//        val views = RemoteViews(context.packageName, R.layout.time_easy_widget_layout)
        Log.d(TAG, "onUpdate: --->textClock")
        appWidgetIds.forEach {
            updateAppWidget(context, appWidgetManager, it)
        }

//        super.onUpdate(context, appWidgetManager, appWidgetIds)
    }

    // 广播接收
    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
//        if (intent.action == ACTION_MANUAL_UPDATE) {
//            Log.d(TAG, "onReceive: 手动触发更新")
//            val appWidgetManager = AppWidgetManager.getInstance(context)
//            val componentName = ComponentName(context, TimeTextWidgetProvider::class.java)
//            val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
//            onUpdate(context, appWidgetManager, appWidgetIds)
//
//            // 继续调度下一次更新
////            schedulePeriodicUpdate(context)
//        }
        if(intent.action=="android.appwidget.action.APPWIDGET_UPDATE"){
            val appWidgetManager = AppWidgetManager.getInstance(context)
            val componentName = ComponentName(context, TimeTextWidgetProvider::class.java)
            val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
            onUpdate(context, appWidgetManager, appWidgetIds)
        }
        Log.d(TAG, "111onReceive: 动作 = ${intent.action}")
    }

    // 初始化（第一次创建
    override fun onEnabled(context: Context) {
        super.onEnabled(context)
        Log.d(TAG, "onEnabled: 组件首次启用，触发更新")
        val appWidgetManager = AppWidgetManager.getInstance(context)
        // 获取所有组件 ID（可能多个实例）
        val appWidgetIds = appWidgetManager.getAppWidgetIds(
            ComponentName(context, TimeTextWidgetProvider::class.java)
        )
        onUpdate(context, appWidgetManager, appWidgetIds)
    }

    private fun updateAppWidget(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int
    ) {
        val views = RemoteViews(context.packageName, R.layout.time_easy_widget_layout)
        // 获取当前帧
//        views.setImageViewResource(R.id.ani_clock, getCurFrameId(curFrame))

        startAnimation(context, views, appWidgetId)

//        views.setOnClickPendingIntent(R.id.ani_clock)
        // 更新（结算！
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }

    private fun getCurFrameId(curFrame: Int): Int {
        return when (curFrame) {
            0 -> R.raw.xhx1
            1 -> R.raw.xhx3
            2 -> R.raw.xhx5
            3 -> R.raw.xhx7
            4 -> R.raw.xhx9
            else -> R.raw.xhx1
        }
    }

    private fun startAnimation(context: Context, views: RemoteViews, appWidgetId: Int) {
        Log.d(TAG, "startAnimation: 进入动画！！")
        handler.post(object : Runnable {
            override fun run() {
                views.setImageViewResource(R.id.ani_clock, getCurFrameId(curFrame))
                curFrame = (curFrame + 1) % totalFrames
                Log.d(TAG, "run: 动画动起来了吗$curFrame")
                AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, views)
                handler.postDelayed(this, 200)
            }
        })
    }
}